package com.example.demo.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.example.demo.bese.BaseActivity;
import com.example.demo.databinding.ActivityHandlerTextBinding;
import com.example.demo.util.TimeRecordUtil;
import com.example.demo.view.TimedPopupWindow;
import com.example.library.utils.SpUtil;

/**
 * @author: xtxiaolu
 * @date: 2023/8/17
 * 描述: 测试线程工具类
 */
public class HandlerTextActivity extends BaseActivity {
    private ActivityHandlerTextBinding binding;
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private TimedPopupWindow timedPopupWindow;
    private String currentInfo;
    private String previousInfo = ""; // 保存上一个信息
    private long previousTime = 0;    // 保存上一个信息的时间戳

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHandlerTextBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        timedPopupWindow = new TimedPopupWindow(this);

        binding.button1.setOnClickListener(view -> {
            mHandler.postDelayed(mRunnable, 200);
        });

        binding.button2.setOnClickListener(view -> {
            Log.d("HandlerTextActivity", "button2 clicked");
            timedPopupWindow.dismiss();
            mHandler.removeCallbacksAndMessages(null);
        });
    }

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            // 在这里执行你需要延迟执行的任务
            onGetInfo();
            mHandler.postDelayed(this, 1000);
        }
    };

    private void onGetInfo() {
        long startTime = System.currentTimeMillis();
        currentInfo = "111111111";

        previousInfo = SpUtil.getString("str");
        if (!TextUtils.isEmpty(previousInfo) &&
                previousInfo.equals(currentInfo) &&
                TimeRecordUtil.getInstance().isExceedTimeInterval(startTime, 3000)) {
//            TimeRecordUtil.getInstance().clearStartTime();
            timedPopupWindow.setType(2)
                    .updateContent("错误提示！")
                    .setDuration(500)
                    .show();
            return;
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        SpUtil.putString("str", currentInfo);
        TimeRecordUtil.getInstance().setStartTime(startTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timedPopupWindow.dismiss();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
